
import time from 'locutus/php/datetime/time';

const { action } = jinghuan.props;

/**
 * 仓库
 */
class warehouse extends jinghuan.AdminController {


    /**
     *
     * @return {QueryBuilder}
     * @private
     */
    _listModel(id = 0) {
        let model = this.db('jh_warehouse')
            .where('status', '>', 0);

        if (id) {
            model.where('id', id).first()
        }

        return model;
    }


    /**
     * 
     */
    @action({ auth: false, login: false })
    async datatable() {
        let model1 = this._listModel();

        let model2 = this.db('jh_warehouse')
            .where('status', '>', 0)
            .count('id as count');

        await this.default_datatable2(model1, model2, [])
    }

    @action({ auth: false, login: false })
    async get_storage() {
        let data = await this.db('jh_warehouse')
            .select('id as value', 'name as title')

        this.callback(data);
    }

    @action({ auth: false })
    async do_add({ }, { name, code }) {
        let model = await this.db('jh_warehouse')
            .insert({
                name,
                code,
                time: time(),
                u_time: time()
            });
        if (model) {
            this.record('添加仓库成功');
            let data = await this._listModel(model[0]);
            this.callback(data, { toast: "message.success.add" });
        } else {
            this.record('添加仓库失败');
            this.callback(false, { toast: "message.error.add" });
        }
    }


    @action({ auth: false })
    async do_edit(GET, { name, code, id }) {
        let model = await this.db('jh_warehouse')
            .where('id', '=', id)
            .update({
                name,
                code,
                u_time: time()
            });

        if (model) {
            this.record('编辑仓库成功');
            let data = await this._listModel(id);
            this.callback(data, { toast: "message.success.edit" });
        } else {
            this.record('编辑仓库失败');
            this.callback(false, { toast: "message.error.edit" });
        }
    }

}

export default warehouse;